package com.tender;

import com.tender.utils.ESOperationTemplate;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

public class A_19_QueryGroupDoc {

    public static void main(String[] args) throws Exception {

        ESOperationTemplate.process(client -> {

            try {
                SearchRequest request = new SearchRequest().indices("user2");
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                // 自定义聚合字段名称 age_groupby
                sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));
                // 不展示原始数据
                sourceBuilder.size(0);
                //设置请求体
                request.source(sourceBuilder);
                //3.客户端发送请求，获取响应对象
                SearchResponse response = client.search(request, RequestOptions.DEFAULT);
                //4.打印响应结果
                SearchHits hits = response.getHits();
                System.out.println(hits);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return null;
        });
    }

}
